const express = require('express');
const router = express.Router();
const mysql = require('mysql2');
const dbConfig = require('../config/database');

const connection = mysql.createConnection(dbConfig);

connection.connect((err) => {
    if (err) {
        console.error('数据库连接失败: ' + err.stack);
        return;
    }
    console.log('已连接到数据库');
});

router.post('/login', async (req, res) => {
    const { username, password } = req.body;
    try {
        const query = 'SELECT * FROM users WHERE username = ? AND password = ?';
        connection.query(query, [username, password], (error, results) => {
            if (error) {
                console.error('Database query error:', error);
                return res.status(500).json({ message: 'Internal server error' });
            }
            if (results.length > 0) {
                res.status(200).json({ message: 'Login successful', token: 'fake-jwt-token', username: results[0].username });
            } else {
                res.status(401).json({ message: 'Invalid credentials' });
            }
        });
    } catch (error) {
        console.error('Unexpected error:', error);
        res.status(500).json({ message: 'Internal server error' });
    }
});

module.exports = router;